package basic.study.wantOffer.chapter5;

/**
 * @ClassName Problem44
 * @Description 数字序列中某一位的数字
 * @Company inspur
 * @Author Kevin
 * @Date 2020/6/4 15:50
 * @Version 1.0
 */
public class Problem44 {
    class DigitsInSequenc {

        public int digitAtIndex(int index) {
            if (index < 0) {
                return -1;
            }
            int m = 1;//m位数
            while (true) {
                int number = numbersOfIntegers(m);
                if (index < m * number) {//看来index属于m位数的数字
                    return getDigit(index, m);
                }
                index -= m * number;
                m++;
            }
        }

        private int numbersOfIntegers(int m) {
            if (m == 1) {
                return 10;
            }
            return (int) (9 * Math.pow(10, m-1));
        }


        private int getDigit(int index, int m) {
            //1.找到第一个m位数数， 2.找到m所在数
            int number = getFirstNumberOfN(m) + index / m;
            //3.得到m对应数值   index在所在数内位置:  m - index % m
            int moveIndex = m - index % m;
            for (int i = 0; i < moveIndex; i++ ) {
                number /= 10;
            }
            return number % 10;
        }

        private int getFirstNumberOfN(int m) {
            if (m == 1) {
                return 0;
            }
            return (int) (1 * Math.pow(10, m-1));
        }


    }
}
